package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        //2、获取对应日期的营业额字符串
        List<Double> turnoverList = new ArrayList<>();

        //查询当天“已完成”状态订单金额的总和
        for (LocalDate date : dateList) {
            //当前日期的开始时间->0:0:0
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            //当前日期的结束时间->23:59:59.9999
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",begintime);
            map.put("end",endtime);
            map.put("status", Orders.COMPLETED);
            //select sum(amount) from orders where order_time between begin and end and status = status
            Double amount = orderMapper.sumByMap(map);
            amount = amount == null ? 0.0 : amount;
            turnoverList.add(amount);

        }

        //3、封装返回结果
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 统计用户数量
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        //2、获取当前日期新增用户数量
        //3、获取截止当前日期用户的总数
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //当前日期的开始时间->0:0:0
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            //当前日期的结束时间->23:59:59.9999
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",endtime);
            //总数：select count(id) from user where create_time < endtime
            Integer totalUser = userMapper.getUserNumber(map);
            totalUserList.add(totalUser);

            map.put("begin",begintime);
            //新增：select count(id) from user where create_time < endtime and create_time > begintime
            Integer newUser = userMapper.getUserNumber(map);
            newUserList.add(newUser);

        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }

    /**
     * 订单数量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getLocalDates(begin, end);

        //当天订单总数
        List<Integer> orderCountList = new ArrayList<>();
        //当天有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();

        for (LocalDate date : dateList) {
            //当前日期的开始时间->0:0:0
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            //当前日期的结束时间->23:59:59.9999
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin",begintime);
            map.put("end",endtime);
            //计算当天所有订单数 select count(id) from orders where order_time > ? and order_time < ?
            Integer ordersNumber = orderMapper.getOrders(map);
            orderCountList.add(ordersNumber);
            //计算当天有效订单数 select count(id) from orders where order_time > ? and order_time < ? and status = 5
            map.put("status",Orders.COMPLETED);
            Integer validOrderNumber = orderMapper.getOrders(map);
            validOrderCountList.add(validOrderNumber);
        }

        //计算订单总数
        Integer ordersum = 0;
        for (Integer order : orderCountList) {
            ordersum += order;
        }
        //计算有效订单数
        Integer validsum = 0;
        for (Integer order : validOrderCountList) {
            validsum += order;
        }
        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if( ordersum != 0) {
            orderCompletionRate = validsum.doubleValue() / ordersum;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(ordersum)
                .validOrderCount(validsum)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 获取时间集合
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getLocalDates(LocalDate begin, LocalDate end) {
        //1、获取当前从begin到end的日期的字符串
        List<LocalDate> dateList = new ArrayList<>();

        dateList.add(begin);
        //判断begin与end是否为同一天
        while (!begin.equals(end)){
            //begin与end不相同，begin后移一天，并添加集合，知道begin==end
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }

    /**
     * 销量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //0、获取当天的min、max
        //当前日期的开始时间->0:0:0
        LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
        //当前日期的结束时间->23:59:59.9999
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);

        //1、sql查询
        Map map = new HashMap();
        map.put("begin",begintime);
        map.put("end",endtime);

        List<GoodsSalesDTO> goodsSalesDTOList = orderDetailMapper.top10(map);

        //2、获取name列表
        String nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.joining(","));
        //3、获取销量列表
        String numberList = goodsSalesDTOList.stream().map(dto -> {
            Integer number = dto.getNumber();
            return String.valueOf(number);
        }).collect(Collectors.joining(","));

        //String numberList = goodsSalesDTOList.stream().map(dto -> String.valueOf(dto.getNumber())).collect(Collectors.joining(","));
        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    /**
     * 导出营业数据报表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //1、查询数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        //获取营业数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN), LocalDateTime.of(endDate, LocalTime.MAX));
        //2、基于已有模板写数据
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try {
            //基于模板创建一个excel
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);

            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(1);
            row.getCell(1).setCellValue("时间：" + beginDate + "至" + endDate);

            XSSFRow row1 = sheet.getRow(3);
            row1.getCell(2).setCellValue(businessData.getTurnover());
            row1.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row1.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow row2 = sheet.getRow(4);
            row2.getCell(2).setCellValue(businessData.getValidOrderCount());
            row2.getCell(4).setCellValue(businessData.getUnitPrice());

            //明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = beginDate.plusDays(i);
                BusinessDataVO businessdatavo = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                XSSFRow row3 = sheet.getRow(i + 7);
                row3.getCell(1).setCellValue(date.toString());
                row3.getCell(2).setCellValue(businessdatavo.getTurnover());
                row3.getCell(3).setCellValue(businessdatavo.getValidOrderCount());
                row3.getCell(4).setCellValue(businessdatavo.getOrderCompletionRate());
                row3.getCell(5).setCellValue(businessdatavo.getUnitPrice());
                row3.getCell(6).setCellValue(businessdatavo.getNewUsers());
            }


            //3、通过输出流将报表下载到客户端浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
